﻿using System;
using System.Collections.Generic;
using UnityEngine;

namespace Core.Net
{
    public partial class RPCMsgManager
    {
        //考虑到优先级，暂时使用list
        private readonly List<OnPushRPCMsgData> onPushRPCMsg = new List<OnPushRPCMsgData>();

        private void EnqueueOnPushRPCMsg(int rpcID, int msgID, ByteBuf param)
        {
            var msg = new OnPushRPCMsgData(rpcID, msgID, param);
            onPushRPCMsg.Add(msg);
            Debug.Log($"#消息队列# 接受服务器消息协议id——{rpcID}");
            // 如果当前没有其他消息被处理，则直接处理此消息
            if (onPushRPCMsg.Count == 1)
            {
                ProcessNextPushRPCMsg();
            }
        }

        private async void ProcessNextPushRPCMsg()
        {
            // 确保当前消息队列不为空
            if (onPushRPCMsg.Count == 0) return;
            // 从队列中获取下一条消息
            var currentMessage = onPushRPCMsg[0];
            string str = String.Empty;
            foreach (var msgData in onPushRPCMsg)
            {
                str += " " + msgData.RPCID.ToString() + ",";
            }
            Debug.Log($"#消息队列# 执行服务器消息协议id——{currentMessage.RPCID}， 当前剩余协议数{onPushRPCMsg.Count},协议：{str}");
            //处理服务器远程调用请求
            await DealServerCallback(currentMessage.RPCID, currentMessage.MSGID, currentMessage.PARAM);
            // 清除一条消息
            onPushRPCMsg.RemoveAt(0);
            // 队列中仍有未处理的消息，则继续处理下一条消息
            if (onPushRPCMsg.Count > 0)
            {
                ProcessNextPushRPCMsg();
            }
        }
    }
}